#include "..\\include\Lib_Clara.h"
#include "..\\include\Dir.h"
#include "..\\include\cfg_items.h"
#include "conf_loader.h"
#include "..\\include\var_arg.h"
#include "gui.h"

const wchar_t *successed_config_path=L"";
const wchar_t *successed_config_name=L"";

int b_temp_f;
const wchar_t *b_temp_path;
const wchar_t *b_temp_fname;
void *b_temp_cfg;
unsigned int b_temp_len;
extern int isSEns9xBook(BOOK * book);
extern int running;
extern int set_pause;

void OnNoExitGui(BOOK * bk, void *)
{
  GUIObject_Destroy( MyBook->yesno);
  running = 0;
  return;
}

void OnYesTurn(BOOK * bk, void *)
{
  GUIObject_Destroy( MyBook->yesno);
  if ((b_temp_f=_fopen(b_temp_path,b_temp_fname,0x204,0x180,0))>=0)
    fwrite(b_temp_f,b_temp_cfg,b_temp_len);
  fclose(b_temp_f);
  set_pause = 0;
}


void CreateTurnQuestion(wchar_t *mess, wchar_t *ask)
{
  set_pause=1;
  MyBook->yesno = CreateYesNoQuestionVA(0,
                                VAR_BOOK( MyBook ),
                                VAR_YESNO_PRE_QUESTION( Str2ID( mess, 0, 0xffff) ),
                                VAR_YESNO_QUESTION( Str2ID( ask, 0, 0xffff) ),
                                VAR_YESNO_YES_ACTION( OnYesTurn ),
                                VAR_YESNO_NO_ACTION( OnNoExitGui ),
                                0);
}

#pragma segment="CONFIG_C"
int LoadConfigData(const wchar_t *path,const wchar_t *fname)
{
  int f;
  char *buf;
  int result=-1;
  void *cfg;
  FSTAT _fstat;
  unsigned int rlen;

  cfg=(char *)__segment_begin("CONFIG_C");

  unsigned int len=(char *)__segment_end("CONFIG_C")-(char *)__segment_begin("CONFIG_C");

  if ((buf=new char[len]))
  {
    if (fstat(path,fname,&_fstat)!=-1)
    {
      if ((f=_fopen(path,fname,0x001,0x180,0))>=0)
      {
        rlen=fread(f,buf,len);
        fclose(f);
        if (rlen!=_fstat.fsize || rlen!=len)  goto L_SAVENEWCFG;
        memcpy(cfg,buf,len);
        result=0;
      }
    }
    else
    {
    L_SAVENEWCFG:
      b_temp_f = f;
      b_temp_path = path;
      b_temp_fname = fname;
      b_temp_cfg = cfg;
      b_temp_len = len;
      CreateTurnQuestion(L"Current .bcfg is not dedicated for this version on SEns9x. It will be replaced.",L"Continue?");
      result = 0;
      /*
      if ((f=_fopen(path,fname,0x204,0x180,0))>=0)
      {
        if (fwrite(f,cfg,len)==len){
          result=0;
        }
        fclose(f);
      }
      */
    }
    delete buf;
  }
  if (result>=0)
  {
    successed_config_path=path;
    successed_config_name=fname;
  }
  return(result);
}


void InitConfig(void)
{
  if (LoadConfigData(GetDir(DIR_ELFS_CONFIG|MEM_INTERNAL),L"SEns9x.bcfg")<0)
  {
    LoadConfigData(GetDir(DIR_ELFS_CONFIG|MEM_EXTERNAL),L"SEns9x.bcfg");
  }
}
